/**
 * @NApiVersion 2.x
 * @NScriptType WorkflowActionScript
 */
define(['N/search', 'N/record', 'N/runtime'
        ,'./so.source.creater.main'],
    function(search, record, runtime, soCreater) {

        function onAction(context) {
            log.debug({title:'text',details:"222"});
            var lang = runtime.getCurrentUser().getPreference('LANGUAGE');
            if (lang == 'zh_CN' || lang == 'zh_TW') {
                var dtl = "\r\n没有面单，请确认操作;";
                var dmt = "\r\n没有母单号，请确认操作;";
                var dsp = "\r\n没有物流商物流方式，无法取消面单！"
                var dmc = "没有找到该物流商匹配的api客户端，请联系管理员;\r\n";
            }else {
                var dtl = "\r\nthe order hasnt tracking label , please confirm your action;";
                var dmt = "\r\nthe order hasnt main tracking number , please confirm your action;";
                var dsp = "\r\nthe order hasnt shipmethod , can not cancel the tracking";
                var dmc = "Carrier doesnt matched api client,please contact the administrator;\r\n";
            }
            var errorMSG = '';

            var rec = context.newRecord;
            var recId = context.newRecord.id;
            var contextText = rec.getValue("custrecord_platform_so_context");
            contextText = JSON.parse(contextText);

            createOrder(recId,contextText,contextText.platform);


        }

        function createOrder(sourceId,order,platform) {
            /*log.debug({
             title: 'context',
             details: JSON.stringify(context)
             });*/
            try{

                var result = soCreater.method.createSalesOrderBySourceContext(order);

                log.audit({
                    title: platform+': result',
                    details: JSON.stringify(result)
                });

                var status ;
                var errorMSG = result.message;
                var storeId = result.storeId;
                if(result.success){
                    status = 2;
                }else{
                    status = 3;
                    var msgindex = errorMSG.indexOf('anonymous');
                    if(msgindex>0){
                        errorMSG = errorMSG.substr(0,msgindex);
                    }
                }
                record.submitFields({
                    type:'customrecord_platform_so_source',
                    id:sourceId,
                    values:{
                        custrecord_platform_so_craete_msg:JSON.stringify(result),
                        custrecord_platform_so_store:storeId,
                        custrecord_platform_so_error_msg:errorMSG,
                        custrecord_platform_so_status:status
                    }
                });

            }catch (e){
                log.error({
                    title:'e',
                    details: JSON.stringify(e)
                });
            }

            //return result;
        }


        return {
            onAction: onAction
        };
    });